package com.xiaolong.cloud.feign.adapter;

import com.alibaba.fastjson2.JSON;
import com.xiaolong.cloud.feign.exception.FeignDecoderException;
import com.xiaolong.cloud.feign.exception.ServiceInvocationProcessException;
import com.xiaolong.common.context.ModelViewResponse;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Along
 */
public class FeignClintFailDecoder extends ErrorDecoder.Default {
    private static final Logger log = LoggerFactory.getLogger(FeignClintFailDecoder.class);

    @Override
    public Exception decode(String methodKey, Response response) {
        try {
            if (Objects.isNull(response.body())) {
                return new FeignDecoderException("Feign错误解码器异常");
            } else {
                String bodyStr = Util.toString(response.body().asReader(Util.UTF_8));

                ModelViewResponse<?> baseResponse;
                try {
                    baseResponse = (ModelViewResponse)JSON.parseObject(bodyStr, ModelViewResponse.class);
                } catch (Exception var6) {
                    return new ServiceInvocationProcessException(bodyStr);
                }
                return new ServiceInvocationProcessException(baseResponse.getMessage());
            }
        } catch (Throwable throwable) {
            throw new ServiceInvocationProcessException(throwable);
        }
    }
}
